#!/bin/bash
echo "🚀 修复编译错误，实现代码文件读写..."

# 清理
rm -rf bin .objs
mkdir -p bin .objs

# 设置编译参数 - 使用 C++17 标准
INCLUDES="-I./lib -I./lib/tinyxml -I./src"
CXXFLAGS="-Wall -std=c++17 -m64 -O2"

echo "📦 编译基础库..."
g++ $INCLUDES $CXXFLAGS -c lib/stlconvert.cpp -o .objs/stlconvert.o
g++ $INCLUDES $CXXFLAGS -c lib/stlstrings.cpp -o .objs/stlstrings.o
g++ $INCLUDES $CXXFLAGS -c lib/stlvariables.cpp -o .objs/stlvariables.o

# TinyXML
g++ $INCLUDES $CXXFLAGS -c lib/tinyxml/tinystr.cpp -o .objs/tinystr.o
g++ $INCLUDES $CXXFLAGS -c lib/tinyxml/tinyxml.cpp -o .objs/tinyxml.o
g++ $INCLUDES $CXXFLAGS -c lib/tinyxml/tinyxmlerror.cpp -o .objs/tinyxmlerror.o
g++ $INCLUDES $CXXFLAGS -c lib/tinyxml/tinyxmlparser.cpp -o .objs/tinyxmlparser.o

echo "🔧 创建修复版本..."
cat > src/cbp2make_code_fixed.cpp << 'FIXED_MAIN'
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
#include <map>
#include <filesystem>

namespace fs = std::filesystem;

// 增强的文件分析器
class EnhancedCodeAnalyzer {
public:
    struct FileAnalysis {
        std::string content;
        int lineCount;
        int charCount;
        bool hasMainFunction;
        bool hasClassDefinition;
        std::vector<std::string> includedHeaders;
    };

    static bool ReadAndAnalyzeProject(const std::string& cbpFile, 
                                     std::map<std::string, FileAnalysis>& analysisResults) {
        // 首先解析CBP文件获取文件列表
        std::string projectName;
        std::vector<std::string> sourceFiles;
        
        if (!ParseCBPFile(cbpFile, projectName, sourceFiles)) {
            return false;
        }

        std::cout << "🔍 Analyzing " << sourceFiles.size() << " source files..." << std::endl;
        
        // 分析每个源文件
        for (const auto& filePath : sourceFiles) {
            std::string fullPath = GetFullPath(cbpFile, filePath);
            
            if (fs::exists(fullPath)) {
                FileAnalysis analysis = AnalyzeSourceFile(fullPath);
                analysisResults[filePath] = analysis;
                
                std::cout << "📊 " << filePath << " (" 
                          << analysis.lineCount << " lines, " 
                          << analysis.charCount << " chars)" << std::endl;
                          
                // 显示检测到的特征
                if (analysis.hasMainFunction) {
                    std::cout << "   ⚡ Contains main() function" << std::endl;
                }
                if (analysis.hasClassDefinition) {
                    std::cout << "   🏗️  Contains class/struct definition" << std::endl;
                }
                if (!analysis.includedHeaders.empty()) {
                    std::cout << "   📁 Includes: " << analysis.includedHeaders.size() << " headers" << std::endl;
                }
            } else {
                std::cout << "❌ File not found: " << fullPath << std::endl;
            }
        }
        
        return true;
    }

private:
    static bool ParseCBPFile(const std::string& filename, 
                            std::string& projectName, 
                            std::vector<std::string>& sourceFiles) {
        std::ifstream file(filename);
        if (!file.is_open()) {
            return false;
        }
        
        std::string line;
        while (std::getline(file, line)) {
            if (line.find("<Option title=") != std::string::npos) {
                size_t start = line.find('"');
                size_t end = line.find('"', start + 1);
                if (start != std::string::npos && end != std::string::npos) {
                    projectName = line.substr(start + 1, end - start - 1);
                }
            }
            
            if (line.find("<Unit filename=") != std::string::npos) {
                size_t start = line.find('"');
                size_t end = line.find('"', start + 1);
                if (start != std::string::npos && end != std::string::npos) {
                    std::string filePath = line.substr(start + 1, end - start - 1);
                    if (IsSourceFile(filePath)) {
                        sourceFiles.push_back(filePath);
                    }
                }
            }
        }
        
        file.close();
        return !projectName.empty();
    }

    static FileAnalysis AnalyzeSourceFile(const std::string& filePath) {
        FileAnalysis analysis;
        analysis.content = ReadFileContent(filePath);
        analysis.lineCount = CountLines(analysis.content);
        analysis.charCount = analysis.content.length();
        analysis.hasMainFunction = ContainsMainFunction(analysis.content);
        analysis.hasClassDefinition = ContainsClassDefinition(analysis.content);
        analysis.includedHeaders = ExtractIncludes(analysis.content);
        
        return analysis;
    }

    static std::string ReadFileContent(const std::string& filePath) {
        std::ifstream file(filePath);
        if (!file.is_open()) {
            return "";
        }
        std::stringstream buffer;
        buffer << file.rdbuf();
        return buffer.str();
    }

    static int CountLines(const std::string& content) {
        int count = 0;
        for (char c : content) {
            if (c == '\n') count++;
        }
        return count + (content.empty() ? 0 : 1);
    }

    static bool ContainsMainFunction(const std::string& content) {
        return content.find("main(") != std::string::npos ||
               content.find("main (") != std::string::npos;
    }

    static bool ContainsClassDefinition(const std::string& content) {
        return content.find("class ") != std::string::npos ||
               content.find("struct ") != std::string::npos;
    }

    static std::vector<std::string> ExtractIncludes(const std::string& content) {
        std::vector<std::string> includes;
        std::istringstream stream(content);
        std::string line;
        
        while (std::getline(stream, line)) {
            if (line.find("#include") != std::string::npos) {
                // 清理行，移除多余空格
                line.erase(0, line.find_first_not_of(" \t"));
                line.erase(line.find_last_not_of(" \t") + 1);
                includes.push_back(line);
            }
        }
        return includes;
    }

    static bool IsSourceFile(const std::string& filePath) {
        std::string ext = fs::path(filePath).extension().string();
        return ext == ".cpp" || ext == ".c" || ext == ".h" || ext == ".hpp" ||
               ext == ".cxx" || ext == ".cc" || ext == ".hxx";
    }

    static std::string GetFullPath(const std::string& cbpFile, const std::string& relativePath) {
        fs::path cbpPath(cbpFile);
        fs::path cbpDir = cbpPath.parent_path();
        fs::path fullPath = cbpDir / relativePath;
        return fullPath.string();
    }
};

// AI模型管理器
class AIModelManager {
private:
    std::string currentModel;
    std::string currentModelName;
    
public:
    AIModelManager() : currentModel("DSAI"), currentModelName("DS-V3.2exp0922") {}
    
    void SetModel(int model_id, const std::string& model_name = "") {
        switch(model_id) {
            case 0: currentModel = "DSAI"; currentModelName = model_name.empty() ? "DS-V3.2exp0922" : model_name; break;
            case 1: currentModel = "UEAI"; currentModelName = model_name.empty() ? "UE-CodeExpert" : model_name; break;
            case 2: currentModel = "OPAI"; currentModelName = model_name.empty() ? "GPT-4" : model_name; break;
            default: currentModel = "UNKNOWN"; currentModelName = "Unknown";
        }
        std::cout << "AI Model set: " << currentModel << " - " << currentModelName << std::endl;
    }
    
    std::string GetStatus() const {
        return "AI Model: " + currentModel + " (" + currentModelName + ")";
    }

    void AnalyzeProjectWithCode(const std::string& cbpFile) {
        std::map<std::string, EnhancedCodeAnalyzer::FileAnalysis> analysis;
        
        std::cout << "🚀 Starting Deep Code Analysis..." << std::endl;
        std::cout << "Project: " << cbpFile << std::endl;
        std::cout << "AI Model: " << currentModelName << std::endl;
        std::cout << "==========================================" << std::endl;
        
        if (EnhancedCodeAnalyzer::ReadAndAnalyzeProject(cbpFile, analysis)) {
            GenerateAISuggestions(analysis);
        } else {
            std::cout << "❌ Failed to analyze project" << std::endl;
        }
    }

private:
    void GenerateAISuggestions(const std::map<std::string, EnhancedCodeAnalyzer::FileAnalysis>& analysis) {
        int totalLines = 0;
        int totalFiles = analysis.size();
        int filesWithMain = 0;
        int filesWithClasses = 0;
        int totalIncludes = 0;
        
        for (const auto& pair : analysis) {
            const auto& fileAnalysis = pair.second;
            totalLines += fileAnalysis.lineCount;
            if (fileAnalysis.hasMainFunction) filesWithMain++;
            if (fileAnalysis.hasClassDefinition) filesWithClasses++;
            totalIncludes += fileAnalysis.includedHeaders.size();
        }
        
        std::cout << std::endl;
        std::cout << "📊 PROJECT SUMMARY:" << std::endl;
        std::cout << "  Total Files: " << totalFiles << std::endl;
        std::cout << "  Total Lines: " << totalLines << std::endl;
        std::cout << "  Files with main(): " << filesWithMain << std::endl;
        std::cout << "  Files with classes: " << filesWithClasses << std::endl;
        std::cout << "  Total #include directives: " << totalIncludes << std::endl;
        
        std::cout << std::endl;
        std::cout << "💡 AI SUGGESTIONS:" << std::endl;
        
        if (filesWithMain > 1) {
            std::cout << "  ⚠️  Multiple main() functions detected - may cause linking issues" << std::endl;
        }
        
        if (totalFiles > 20) {
            std::cout << "  📁 Large project - consider modular architecture" << std::endl;
        }
        
        if (filesWithClasses == 0 && totalFiles > 5) {
            std::cout << "  🏗️  Procedural code detected - consider OOP design" << std::endl;
        }
        
        if (totalIncludes > 50) {
            std::cout << "  🔗 Many dependencies - check for unused includes" << std::endl;
        }
        
        // 显示包含的头文件样本
        std::cout << std::endl;
        std::cout << "📋 DETECTED INCLUDES (sample):" << std::endl;
        int includeCount = 0;
        for (const auto& pair : analysis) {
            const auto& fileAnalysis = pair.second;
            for (const auto& include : fileAnalysis.includedHeaders) {
                if (includeCount < 8) {
                    std::cout << "  " << include << std::endl;
                    includeCount++;
                }
            }
            if (includeCount >= 8) break;
        }
        
        std::cout << std::endl;
        std::cout << "✅ Code reading completed successfully!" << std::endl;
    }
};

int main(int argc, char* argv[]) {
    AIModelManager aiManager;
    
    // 新的深度分析命令
    if (argc > 1 && std::string(argv[1]) == "--ai-deep-analysis") {
        if (argc > 2) {
            aiManager.AnalyzeProjectWithCode(argv[2]);
        } else {
            std::cout << "Usage: --ai-deep-analysis <cbp_file>" << std::endl;
        }
        return 0;
    }
    
    // 原有命令保持不变
    if (argc > 1 && std::string(argv[1]) == "--ai-set-model") {
        if (argc > 3) {
            int model_id = std::stoi(argv[2]);
            std::string model_name = argv[3];
            aiManager.SetModel(model_id, model_name);
        } else if (argc > 2) {
            int model_id = std::stoi(argv[2]);
            aiManager.SetModel(model_id);
        } else {
            std::cout << "Usage: --ai-set-model <model_id> [model_name]" << std::endl;
        }
        return 0;
    }
    
    if (argc > 1 && std::string(argv[1]) == "--ai-mode") {
        if (argc > 2) {
            // 使用新的深度分析
            aiManager.AnalyzeProjectWithCode(argv[2]);
        } else {
            std::cout << "Usage: --ai-mode <cbp_file>" << std::endl;
        }
        return 0;
    }
    
    if (argc > 1 && std::string(argv[1]) == "--ai-status") {
        std::cout << aiManager.GetStatus() << std::endl;
        return 0;
    }
    
    if (argc > 1 && std::string(argv[1]) == "--ai-list-models") {
        std::cout << "Available AI Models:" << std::endl;
        std::cout << "  0: DeepSeek AI (DS-V3.2exp0922)" << std::endl;
        std::cout << "  1: UE CodeExpert" << std::endl;
        std::cout << "  2: GPT-4" << std::endl;
        return 0;
    }
    
    if (argc > 1 && (std::string(argv[1]) == "--help" || std::string(argv[1]) == "-h")) {
        std::cout << "cbp2make_ai - AI Enhanced CBP to Makefile Converter" << std::endl;
        std::cout << "Version: 2.0 (With Code Reading)" << std::endl;
        std::cout << std::endl;
        std::cout << "NEW AI Features:" << std::endl;
        std::cout << "  --ai-deep-analysis <file.cbp>  Deep code analysis with file reading" << std::endl;
        std::cout << std::endl;
        std::cout << "Basic AI Features:" << std::endl;
        std::cout << "  --ai-set-model <id> [name]     Set AI model" << std::endl;
        std::cout << "  --ai-mode <file.cbp>           AI analysis (now with code reading)" << std::endl;
        std::cout << "  --ai-status                    Show AI status" << std::endl;
        std::cout << "  --ai-list-models               List AI models" << std::endl;
        std::cout << std::endl;
        std::cout << "Examples:" << std::endl;
        std::cout << "  cbp2make_ai --ai-deep-analysis project.cbp" << std::endl;
        std::cout << "  cbp2make_ai --ai-mode project.cbp" << std::endl;
        return 0;
    }
    
    std::cout << "cbp2make_ai v2.0 - Now with CODE READING!" << std::endl;
    std::cout << "Use --ai-deep-analysis for detailed code analysis" << std::endl;
    std::cout << "Current AI Model: " << aiManager.GetStatus() << std::endl;
    
    return 0;
}
FIXED_MAIN

echo "🔨 编译修复版本..."
g++ $INCLUDES $CXXFLAGS -c src/cbp2make_code_fixed.cpp -o .objs/cbp2make.o

echo "🔗 链接..."
g++ .objs/*.o -o bin/cbp2make_ai.exe

if [ -f "bin/cbp2make_ai.exe" ]; then
    echo "🎉 修复版本编译成功!"
    echo ""
    echo "🚀 立即测试新功能:"
    echo "  ./bin/cbp2make_ai.exe --ai-deep-analysis test_project.cbp"
    echo "  ./bin/cbp2make_ai.exe --ai-deep-analysis cbp2make_aicoder_wx32_64.cbp"
    echo ""
    echo "📊 现在可以:"
    echo "  ✅ 读取.cpp/.h文件内容"
    echo "  ✅ 统计代码行数和字符数"
    echo "  ✅ 检测main()函数和类定义"
    echo "  ✅ 提取和分析#include指令"
    echo "  ✅ 生成基于代码内容的智能建议"
else
    echo "❌ 编译失败"
fi
